package net.moonbiter.ebs.protocols.httpparams.tree.building;

import java.io.File;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.moonbiter.ebs.NamingUtil;
import net.moonbiter.ebs.NodeName;
import net.moonbiter.ebs.protocols.httpparams.tree.StringLeaf;
import net.moonbiter.ebs.protocols.httpparams.tree.Tree;
import net.moonbiter.ebs.protocols.httpparams.tree.building.ParamsTreeBuilder;
import net.moonbiter.ebs.protocols.httpparams.tree.building.UploadedFileTreeBuilder;
import net.moonbiter.ebs.validation.ValidationException;

/**
 * Classe che utilizza <code>ParamsTreeBuilder</code>
 * e <code>ParamsTreeBuilder</code> per generare l'albero
 * dei parametri.
 * 
 * @author federico tomassetti
 */
public class HttpTreeBuilder {
	private ParamsTreeBuilder paramsBuilder;
	private UploadedFileTreeBuilder filesBuilder;

	public HttpTreeBuilder(File tmpDirectoryValue, int sizeThresholdValue,
			int maxSize) {
		paramsBuilder = new ParamsTreeBuilder();
		filesBuilder = new UploadedFileTreeBuilder(tmpDirectoryValue,
				sizeThresholdValue, maxSize);
	}

	@SuppressWarnings("unchecked")
	public Tree buildTree(HttpServletRequest request)
			throws ValidationException {
		final Map<String, String[]> httpParams = request.getParameterMap();
		Tree tree = paramsBuilder.buildParamsTree(httpParams);
		filesBuilder.buildUploadedFileTree(request, tree);
		addUrlsPortions(request, tree);
		return tree;
	}

	private void addUrlsPortions(HttpServletRequest request, Tree tree) {
		String contextPath = request.getContextPath();
		String completeUri = request.getRequestURI();
		String relativeUri = completeUri.substring(contextPath.length());

		tree.add(new NodeName("relativeUrl"), new StringLeaf(
				new String[] { relativeUri }));

		String[] urlPortions = relativeUri.split("/");
		for (int i = 0; i < urlPortions.length; i++) {
			NodeName nn = new NodeName(NamingUtil.elementName("urlPortions", i));
			tree.add(nn, new StringLeaf(new String[] { urlPortions[i] }));
		}
	}

}
